package com.itheima.service.mongo.impl;

import cn.hutool.core.util.RandomUtil;
import com.itheima.domain.mongo.PeachblossomSound;
import com.itheima.service.mongo.SoundService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

@Service
public class SoundServiceImpl implements SoundService {

    @Autowired
    private MongoTemplate mongoTemplate;
    /**
     * 保存语音
     * @param peachSound
     */
    @Override
    public void saveSound(PeachblossomSound peachSound) {
        //1.补充语音属性created
        peachSound.setCreated(System.currentTimeMillis());
        mongoTemplate.save(peachSound);
    }

    /**
     * 随机获取语音
     */
    @Override
    public PeachblossomSound findSound(Long userId) {
        //1.查询语音总数，排除自己的
        Query query = new Query(
                Criteria.where("userId").ne(userId)
        );
        long count = mongoTemplate.count(query, PeachblossomSound.class);
        //2.生成随机数（跳过的数）
        if (count==0) {
            return null;
        }
        long random = RandomUtil.randomLong(0, count);
        query.skip(random).limit(1);
        //3.查询并返回
        PeachblossomSound sound = mongoTemplate.findAndRemove(query, PeachblossomSound.class);
        return sound;
    }
}
